from PySide6.QtWidgets import QDialog, QFileDialog, QMessageBox
from pyui.noise_dialog_ui import Ui_NoiseDialog
import sys
import os
import datetime
from workers.process_worker import ProcessWorker

class NoiseDialog(QDialog, Ui_NoiseDialog):
    def __init__(self, parent=None, log_widget=None):
        super().__init__(parent)
        self.setupUi(self)
        self.log_widget = log_widget
        self.inBrowse.clicked.connect(self.browse_input)
        self.outBrowse.clicked.connect(self.browse_output)
        self.startBtn.clicked.connect(self.run_noise)
        self.worker = None

    def browse_input(self):
        file, _ = QFileDialog.getOpenFileName(self, "选择FITS文件", "", "FITS Files (*.fits)")
        if file:
            self.inEdit.setText(file)

    def browse_output(self):
        directory = QFileDialog.getExistingDirectory(self, "选择输出目录")
        if directory:
            self.outEdit.setText(directory)

    def run_noise(self):
        fits_file = self.inEdit.text().strip()
        out_dir = self.outEdit.text().strip()
        if not fits_file or not os.path.isfile(fits_file):
            QMessageBox.warning(self, "参数错误", "请选择有效的输入FITS文件！")
            return
        if not out_dir:
            out_dir = os.path.dirname(fits_file)  # 默认用输入文件所在目录
        if self.log_widget:
            self.log_widget.append(f"开始进行Bias/Noise处理")
        cmd = ['python3', os.path.abspath("util/getNoise.py"), fits_file]
        self.startBtn.setEnabled(False)
        self.worker = ProcessWorker(cmd, cwd=out_dir)
        self.worker.output_signal.connect(self.append_log)
        self.worker.finished_signal.connect(lambda code: self.process_finished(code, out_dir))
        self.worker.start()
        self.accept()  # 立即关闭对话框

    def append_log(self, text):
        if self.log_widget:
            self.log_widget.append(text)
        else:
            QMessageBox.information(self, "运行结果", text)

    def process_finished(self, code, result_dir):
        self.startBtn.setEnabled(True)
        if code == 0:
            self.append_log(f"Bias/Noise处理完成，结果保存在: {result_dir}")
        else:
            self.append_log("Bias/Noise处理失败或中断。") 